package com.guangfeng.yql.comm.util;

import com.github.pagehelper.Page;
import com.guangfeng.yql.comm.port.PageTransform;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;

import java.util.List;

public class CopyUtils {

    @SneakyThrows
    public static <T> T copy(Object obj, Class<T> clazz) {
        T instance = clazz.newInstance();
        BeanUtils.copyProperties(obj, instance);
        return instance;
    }

    public static <T> List<T> copyPage(List list, Class<T> clazz) {
        List<T> page = getPage(list);
        list.forEach(data -> page.add(copy(data, clazz)));
        return page;
    }

    @SneakyThrows
    public static <T> List<T> copyPage(PageTransform<T> transform) {
        return transform.transform();
    }

    public static <T> List<T> getPage(List list) {
        Page<T> result = new Page<>();
        if (list instanceof Page) {
            Page page = (Page) list;
            result.setTotal(page.getTotal());
        } else {
            result.setTotal(list.size());
        }
        return result;
    }

}
